﻿// Utilities/EncryptionHelper.cs

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace DatabaseManager.Utilities
{
    public static class EncryptionHelper
    {
        // .NET Framework 4.8 中建议密钥长度为128/256位，这里保持16字节(128位)
        private static readonly string DefaultKey = "your-secret-key-123456"; // 确保至少16字符

        /// <summary>
        /// AES 加密
        /// </summary>
        public static string Encrypt(string plainText, string key = null)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException(nameof(plainText));

            // 替换 key ??= DefaultKey; 为传统写法
            if (key == null)
            {
                key = DefaultKey;
            }

            // 确保密钥长度为16字节(128位)
            var keyBytes = Encoding.UTF8.GetBytes(key.PadRight(16).Substring(0, 16));

            using (var aes = new AesManaged())
            {
                aes.Key = keyBytes;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.GenerateIV(); // 生成随机IV

                var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (var ms = new MemoryStream())
                {
                    // 先写入IV，解密时需要用到
                    ms.Write(aes.IV, 0, aes.IV.Length);

                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    using (var sw = new StreamWriter(cs))
                    {
                        sw.Write(plainText);
                    }

                    return Convert.ToBase64String(ms.ToArray());
                }
            }
        }

        /// <summary>
        /// AES 解密
        /// </summary>
        public static string Decrypt(string cipherText, string key = null)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException(nameof(cipherText));

            // 替换 key ??= DefaultKey; 为传统写法
            if (key == null)
            {
                key = DefaultKey;
            }

            var keyBytes = Encoding.UTF8.GetBytes(key.PadRight(16).Substring(0, 16));
            var cipherBytes = Convert.FromBase64String(cipherText);

            using (var aes = new AesManaged())
            {
                aes.Key = keyBytes;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                // 从加密数据中读取IV（前16字节）
                var iv = new byte[aes.BlockSize / 8];
                Array.Copy(cipherBytes, 0, iv, 0, iv.Length);
                aes.IV = iv;

                var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                // 解密数据部分（排除前面的IV）
                using (var ms = new MemoryStream(cipherBytes, iv.Length, cipherBytes.Length - iv.Length))
                using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                using (var reader = new StreamReader(cs))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}
